using System;
using System.Collections.Generic;
using System.Linq;
#if XNA
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
#else
using SilverArcade.SilverSprite;
using SilverArcade.SilverSprite.Graphics;
using SilverArcade.SilverSprite.Content;
using SilverArcade.SilverSprite.Input;
#endif


namespace CakeAnimation
{

    public class Animation
    {
        public string Name;
        KeyFrameController m_Controller;
        public List<KeyFrame> m_Keyframes;
        public bool Loopable;


        public Animation(string name, List<KeyFrame> kfs)
        {
            Name = name;
            m_Controller = new KeyFrameController();
            m_Keyframes = kfs;
        }

        public override string ToString()
        {
            return Name;
        }

        public void Update(AnimationContext context)
        {

        }

        public int GetKeyFrameAt(float time)
        {
            for (int i = 0; i < m_Keyframes.Count; i++)
            {
                if (m_Keyframes[i].Time > time)
                {
                    return i;
                }
            }

            return m_Keyframes.Count;
        }

        public int GetKeyFrameBeforeTime(float time)
        {
            for (int i = 0; i < m_Keyframes.Count; i++)
            {
                if (m_Keyframes[i].Time > time)
                {
                    return (i - 1);
                }
            }

            return m_Keyframes.Count - 1;
        }

        public KeyFrame GetLastKeyframe()
        {
            return m_Keyframes[m_Keyframes.Count - 1];
        }

        public float GetDuration()
        {
            return GetLastKeyframe().Time;
        }

        public void GetPoseAt(float time, Skeleton outPose)
        {
            for (int i = 0; i < m_Keyframes.Count; i++)
            {
                KeyFrame kf = m_Keyframes[i];

                if (kf.Time > time)
                {
                    KeyFrame prevKf = m_Keyframes[i - 1];
                    float t = (time - prevKf.Time) / (kf.Time - prevKf.Time);
                    m_Controller.InterplateSkeleton(outPose, prevKf.Pose, kf.Pose, t);

                    return;
                }
            }

            m_Controller.InterplateSkeleton(outPose, GetLastKeyframe().Pose, GetLastKeyframe().Pose, 0.0f);
        }
    }
}
